package com.wnxy.dynamic.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class App2_cglib {
    public static void main(String[] args) {
        // 目标对象
        OrderServiceImpl2 orderService = new OrderServiceImpl2();
        System.out.println("orderService.getClass() = " + orderService.getClass());

        // cglib动态代理
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(OrderServiceImpl2.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(
                    Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("记录日志：start");
                // 执行目标对象的方法
                Object retValue = method.invoke(orderService, args);
                System.out.println("记录日志：end");
                return retValue;
            }
        });

        // 创建代理: class Cglib extends OrderServiceImpl2
        OrderServiceImpl2 proxy = (OrderServiceImpl2) enhancer.create();
        System.out.println("proxy.getClass() = " + proxy.getClass());
        // 执行代理的方法
        proxy.save();
    }
}
